import { PrismaService } from 'nestjs-prisma'
import { Page, type PageDto } from '@libs/lhy-core'
import { Injectable } from '@nestjs/common'
import { Prisma } from '@prisma/client'
import { DomainModel } from '../model'

@Injectable()
export class FlowBoardDataDao {
  get table() {
    return this.prismaService.flowBoardData
  }

  constructor(private readonly prismaService: PrismaService) {}

  /**
   * 分页查询，返回结果中不包含data
   * @param page
   * @param data
   * @returns
   */
  async page(pageDto: PageDto, data: Prisma.FlowBoardDataWhereInput) {
    const page = new Page<DomainModel.FlowBoardData>(pageDto)

    page.totals = await this.table.count({
      where: data,
    })
    page.records = await this.table.findMany({
      select: {
        id: true,
        label: true,
        createTime: true,
        platform: true,
        project: true,
        dataHash: true,
      },
      where: data,
      skip: page.skip,
      take: page.take,
      orderBy: [
        {
          createTime: 'desc',
        },
      ],
    })

    return page
  }

  /**
   * 根据ID获取数据
   * @param id
   * @returns
   */
  getById(id: number): Promise<DomainModel.FlowBoardData | null> {
    return this.table.findUnique({
      where: {
        id,
      },
    })
  }

  /**
   * 根据ID更新数据
   * @param id
   * @param data
   * @returns
   */
  updateById(id: number, data: Prisma.FlowBoardDataUpdateInput): Promise<DomainModel.FlowBoardData> {
    return this.table.update({
      where: {
        id,
      },
      data: {
        project: data.project,
        label: data.label,
        data: data.data,
        dataHash: data.dataHash,
      },
    })
  }

  /**
   * 保存数据
   * @param data
   * @returns
   */
  save(data: Prisma.FlowBoardDataCreateInput): Promise<DomainModel.FlowBoardData> {
    return this.table.create({
      data: {
        platform: data.platform,
        project: data.project,
        label: data.label,
        data: data.data,
        dataHash: data.dataHash,
      },
    })
  }

  /**
   * 根据ID删除数据
   * @param ids
   * @param data
   * @returns
   */
  deleteByIds(ids: number[], data: { platform: string; project?: string }) {
    if (!ids.length) {
      return Promise.resolve()
    }

    return this.table.deleteMany({
      where: {
        platform: data.platform,
        project: data.project,
        id: {
          in: ids,
        },
      },
    })
  }
}
